/*
 * Copyright 2009 Lukasz Wozniak
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 *
 * http://www.apache.org/licenses/LICENSE-2.0 
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */
package pl.sind.http.basic;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;

import pl.sind.http.HttpRequestException;
import pl.sind.http.RequestWrapper;

/**
 * Basic implementation wrapping HttpURLConnection.
 * 
 * @author Lukasz Wozniak
 * 
 */
public class SimpleRequestWrapper implements RequestWrapper {

	private HttpURLConnection connection;

	/**
	 * Constructor setting underlying connection.<br/>
	 * You'd better not give null here ;)
	 * 
	 * @param connection
	 *            to be used by wrapper.
	 */
	public SimpleRequestWrapper(HttpURLConnection connection) {
		super();
		this.connection = connection;
	}

	/* (non-Javadoc)
	 * @see pl.lwozniak.http.RequestWrapper#getHeader(java.lang.String)
	 */
	public String getHeader(String name) {
		return connection.getRequestProperty(name);
	}

	/* (non-Javadoc)
	 * @see pl.lwozniak.http.RequestWrapper#getOutputStream()
	 */
	public OutputStream getOutputStream() throws HttpRequestException {
		try {
			if (!connection.getDoOutput()) {
				connection.setDoOutput(true);
			}
			return connection.getOutputStream();
		} catch (IOException e) {
			throw new HttpRequestException(e);
		}
	}

	/* (non-Javadoc)
	 * @see pl.lwozniak.http.RequestWrapper#setHeader(java.lang.String, java.lang.String)
	 */
	public void setHeader(String name, String value) {
		connection.setRequestProperty(name, value);
	}

}
